package dai.samples.reporters;

import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Slf4jReporter;
import com.codahale.metrics.Timer;
import dai.samples.metrics.TimersTest;
import org.slf4j.LoggerFactory;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author daify
 * @date 2022-05-09
 */
public class Slf4jReporters {


    public static Random random = new Random();

    public static void main(String[] args) throws InterruptedException {
        // 创建一个度量
        MetricRegistry registry = new MetricRegistry();
        // 注册到控制台中
        Slf4jReporter reporter = Slf4jReporter.forRegistry(registry)
                .outputTo(LoggerFactory.getLogger("com.example.metrics"))
                .convertRatesTo(TimeUnit.SECONDS)
                .convertDurationsTo(TimeUnit.MILLISECONDS)
                .build();
        // 每5秒输出一次结果
        reporter.start(5, TimeUnit.SECONDS);

        Timer timer = registry.timer(MetricRegistry.name(TimersTest.class,"get-latency"));
        Timer.Context ctx;

        while(true){
            ctx = timer.time();
            Thread.sleep(random.nextInt(1000));
            ctx.stop();
        }
    }

}
